package org.zuel.huhuForum.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.zuel.huhuForum.component.SendMsg;
import org.zuel.huhuForum.constant.CommunityConstant;
import org.zuel.huhuForum.model.User;
import org.zuel.huhuForum.param.Event;
import org.zuel.huhuForum.param.Page;
import org.zuel.huhuForum.service.IUserService;
import org.zuel.huhuForum.service.Impl.FollowService;
import org.zuel.huhuForum.util.HostHolder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
@RestController
@RequestMapping("/follow")
@Api(tags = "关注")
public class FollowController implements CommunityConstant {

    @Autowired
    private FollowService followService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private IUserService userService;

    @Autowired
    private SendMsg eventProducer;

    /**
     * 关注
     * @param entityType
     * @param entityId
     * @return
     */
    @CrossOrigin
    @PostMapping("/follow")
    @ApiOperation(value = "关注")
    public Map<String, String> follow(@RequestParam(name="entityType", required = true)int entityType,
                         @RequestParam(name="entityId", required = true)int entityId) {
        User user = hostHolder.getUser();

        followService.follow(user.getId(), entityType, entityId);

        // 触发关注事件（系统通知）
        Event event = new Event()
                .setTopic(TOPIC_FOLLOW)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(entityType)
                .setEntityId(entityId)
                .setEntityUserId(entityId);
        eventProducer.fireEvent(event);
        Map<String,String>model =new HashMap<>();
        model.put("msg", "codeMsg");
        model.put("code", "200");
        model.put("data","已关注");
        return  model;
    }

    /**
     * 取消关注
     * @param entityType
     * @param entityId
     * @return
     */
    @CrossOrigin
    @PostMapping("/unfollow")
    @ApiOperation(value = "取消关注")
    public Map<String, String> unfollow(@RequestParam(name="entityType", required = true)int entityType,
                                        @RequestParam(name="entityId", required = true) int entityId) {
        User user = hostHolder.getUser();

        followService.unfollow(user.getId(), entityType, entityId);

        Map<String,String>model =new HashMap<>();
        model.put("msg", "codeMsg");
        model.put("code", "200");
        model.put("data","已取消关注");
        return  model;
    }

    /**
     * 某个用户的关注列表（人）
     * @param userId
     * @param current
     * @return
     */
    @CrossOrigin
    @PostMapping("/folls")
    @ApiOperation(value = "某个用户的关注列表（人）")
    @ResponseBody
    public Map<String, Object> getFollowees(@RequestParam(name="userId",required = false,defaultValue = "0") Integer userId,
                             @RequestParam(name = "current",required = false,defaultValue = "1") Integer current) {
        Map<String, Object> model=new HashMap<>();
        User user;
        if(userId==0){
            user=hostHolder.getUser();
            userId=user.getId();
        }else {
            user=userService.findUserById(userId);

            if (user == null) {
                throw new RuntimeException("该用户不存在");
            }

            //其他用户无法访问被拉黑用户
            if (user.getStatus().equals(TYPE_TWE)){
                model.put("data", "该用户已被拉黑！");
                model.put("code", "23");
                model.put("msg", "error");
                return model;
            }
        }
        Page page=new Page();
        page.setCurrent(current);
        page.setLimit(10);
        page.setPath("/followees/" + userId);
        page.setRows((int) followService.findFolloweeCount(userId, ENTITY_TYPE_USER));
        model.put("page", page);
        // 获取关注列表
        List<Map<String, Object>> userList = followService.findFollowees(userId, page.getOffset(), page.getLimit());

        if (userList != null) {
            for (Map<String, Object> map : userList) {
               User u = (User) map.get("user"); // 被关注的用户
                map.put("hasFollowed", hasFollowed(u.getId())); // 判断当前登录用户是否已关注这个关注列表中的某个用户
            }
        }
        model.put("userList", userList);
        return model;
    }

    /**
     * 某个用户的粉丝列表
     * @param userId
     * @param current
     * @return
     */
    @CrossOrigin
    @PostMapping("/followers")
    @ApiOperation(value = "某个用户的粉丝列表")
    public Map<String, Object> getFollowers(@RequestParam(name="userId",required = false,defaultValue = "0") Integer userId,
                             @RequestParam(name = "current",required = false,defaultValue = "1") Integer current) {
        Map<String, Object> model=new HashMap<>();
        User user;
        if(userId.equals(0)){
            user=hostHolder.getUser();
            userId=user.getId();
        }else {
            user=userService.findUserById(userId);

            if (user == null) {
                throw new RuntimeException("该用户不存在");
            }

            //其他用户无法访问被拉黑用户
            if (user.getStatus().equals(TYPE_TWE)){
                model.put("data", "该用户已被拉黑！");
                model.put("code", "23");
                model.put("msg", "error");
                return model;
            }
        }
        Page page=new Page();
        page.setLimit(5);
        page.setPath("/followers/" + userId);
        page.setRows((int) followService.findFollowerCount(ENTITY_TYPE_USER, userId));
        model.put("page", page);
        // 获取关注列表
        List<Map<String, Object>> userList = followService.findFollowers(userId, page.getOffset(), page.getLimit());

        if (userList != null) {
            for (Map<String, Object> map : userList) {
                User u = (User) map.get("user"); // 被关注的用户
                map.put("hasFollowed", hasFollowed(u.getId())); // 判断当前登录用户是否已关注这个关注列表中的某个用户
            }
        }
        model.put("userList", userList);
        return model;
    }

    /**
     * 判断当前登录用户是否已关注某个用户
     * @param userId 某个用户
     * @return
     */
    private boolean hasFollowed(int userId) {
        if (hostHolder.getUser() == null) {
            return false;
        }

        return followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
    }


}
